const {
	readFile,
	writeFile
} = require('node:fs')
const {
	basename
} = require('node:path')

function openFile(options) {
	return new Promise((resolve, reject) => {
		const paths = utools.showOpenDialog(options)
		const path = paths[0]
		if (path) {
			readFile(path, (err, data) => {
				if (err) {
					reject(err)
					return
				}
				const blob = new Blob([data], {
					type: 'application/octet-stream'
				})
				resolve(new File([blob], basename(path)))
			})
		}
	})
}

async function downloadFile(data, name) {
	const target = utools.showSaveDialog({
		title: '请选择文件保存位置',
		buttonLabel: '保存',
		defaultPath: name
	})
	if (!target) {
		return Promise.reject()
	}
	return new Promise(async (resolve, reject) => {
		writeFile(target, new Uint8Array(data), e => {
			if (e) {
				return reject(e)
			}
			resolve(target)
		})
	})
}

window.preload = {
	openFile,
	downloadFile
}